package com.sali.DFS;

// 岛屿数量
public class LeetCode_200 {


    public static void main(String[] args) {
        char[][] grid = new char[][]{
                {'1', '1', '1', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}
        };

        int i = numIslands(grid);
        System.out.println(i);
    }

    public static int numIslands(char[][] grid) {

        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    dfs(grid, i, j);
                }
            }
        }
        return count;
    }

    private static void dfs(char[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {
            return;
        }

        if (grid[i][j] != '1') {
            return;
        }


        grid[i][j] = '0';

        int[] xDir = new int[]{1, -1, 0, 0};
        int[] yDir = new int[]{0, 0, 1, -1};

        for (int z = 0; z < 4; z++) {
            dfs(grid, i + xDir[z], j + yDir[z]);
        }
    }
}
